import React from "react"
import Taro from "@tarojs/taro"
import GpContainer from "@/components/GpContainer"
import { Image, Navigator, Text, View } from "@tarojs/components"
import { Grid } from "@taroify/core"
import { ArrowRight } from "@taroify/icons"
import GpBlockTitle from "@/components/GpBlockTitle"
import GpSchoolItem from "@/components/GpSchoolItem"
import GpInstitutionItemPure from "@/components/GpInstitutionItemPure"
import GpPagination from "@/components/GpPagination"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpTabbar from "@/components/GpTabbar"
import { cloneDeep, setPageMeta } from "@/utils/common"
import { getExplainDetail } from "@/apis/index"
import { pageMapper } from "@/constants/pageMap"
import { commonUrls, makePagePath } from "@/utils/router"
import clsx from "clsx"
import GpHtmlRenderer from "@/components/GpHtmlRenderer"
import styles from "./index.module.scss"

const ports = [{ text: "专业解读" }]
const arrowSize = Taro.pxTransform(18)
const pageSize = 6
type IDetail = {
  id: number
  picture: string
  name: string
  introduce: string
  /** 报考相关 */
  enrollInfo: IHtmlBlockContentable["content"]
}
type IState = {
  pagination: IPagination
  detail: IDetail | null
  /** 专业集合 */
  subjects: any[]
  /** 就业方向 */
  directions: any[]
  /** 学习资料 */
  articles: any[]
  /** 推荐机构 */
  agencys: any[]
  /** 推荐院校 */
  schools: any[]
  /** 分页显示的专业集合 */
  showSubjects: any[]
}
type IData = {
  id: string
}
/** 具体专业解读 如美术解读 */
class SpecificExplain extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      pagination: {
        page: 1,
        pageCount: 1
      },
      detail: null,
      subjects: [],
      directions: [],
      articles: [],
      agencys: [],
      schools: [],
      showSubjects: []
    }
    this.extData = {
      id: ""
    }
  }
  onShareAppMessage() {}
  onLoad(options: Recordable) {
    this.extData.id = options.id
    this.getDetail()
  }
  componentDidShow() {
    this.setPageInfo(this.state.detail)
  }
  setPageInfo = (detail: INullable<IDetail>) => {
    if (detail) {
      setPageMeta({
        keywords: `${detail.name}前景，${detail.name}报考条件`,
        title: `${detail.name}艺考介绍-${detail.name}艺考分哪些专业-择艺宝`,
        description: `什么是${detail.name}艺考？择艺宝从${detail.name}艺考简介、考试内容、报读专业、就业方向、报考条件、相关资料等多个维度让你快速了解${detail.name}艺考相关信息。`
      })
    }
  }
  getDetail = () => {
    Taro.showLoading()
    getExplainDetail(this.extData.id)
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const _subjects = retData.subjects || []
          _subjects.forEach(l => {
            l.url = makePagePath(pageMapper.proIntro, { id: l.id })
          })
          const _articles = retData.articles || []
          _articles.forEach(l => {
            // 文章类型 1艺考资讯 2艺考问答
            if (l.articleType == 1) {
              l.url = makePagePath(pageMapper.newsDetail, { id: l.articleId })
            } else if (l.articleType == 2) {
              l.url = makePagePath(pageMapper.qaDetail, { id: l.articleId })
            }
          })
          // subjects 需要前台分页处理
          let pageCount = 0
          if (_subjects.length > 0) {
            pageCount = Math.ceil(_subjects.length / pageSize)
          }
          const _showSubjects = _subjects.slice(0, pageSize)
          const enrollInfo = retData.enrollInfo
          const detail = {
            id: retData.id,
            picture: retData.picture,
            name: retData.name,
            // https://github.com/NervJS/taro/issues/7003#issuecomment-1134477341
            introduce: retData.introduce.replace(/\\n/g, "\n"),
            enrollInfo
          }
          this.setState({
            detail,
            subjects: _subjects,
            directions: retData.directions || [],
            articles: _articles,
            schools: retData.schools || [],
            showSubjects: _showSubjects,
            pagination: {
              page: 1,
              pageCount
            },
            agencys: retData.agencys || []
          })
          this.setPageInfo(detail)
        }
      })
      .finally(() => {
        Taro.hideLoading()
      })
  }
  handlePageChange = (page: number) => {
    const _pagination = cloneDeep(this.state.pagination)
    _pagination.page = page
    const showSubjects = this.state.subjects.slice((page - 1) * pageSize, page * pageSize)
    this.setState({
      pagination: _pagination,
      showSubjects
    })
  }
  renderBanner = () => {
    const detail = this.state.detail!
    return (
      <View className="bg-hex-fff pt-32px">
        <View
          className="bg-image w-750px h-421px"
          style={{
            backgroundImage: `url(${detail.picture})`
          }}
        ></View>
      </View>
    )
  }
  renderDesc = () => {
    const detail = this.state.detail!
    const { showSubjects } = this.state
    const len = showSubjects.length
    return (
      <View className="px-30px bg-hex-fff pt-40px">
        <View className="yahei-bold font-bold text-36px text-hex-2c2c35 mb-24px">
          <Text>{detail.name}简介</Text>
        </View>
        <View className="yahei font-normal text-28px leading-48px text-hex-2c2c35">
          <Text decode userSelect selectable>
            {detail.introduce}
          </Text>
        </View>
        {len > 0 ? (
          <View className="mt-48px flex flex-col">
            {showSubjects.map((l, index) => (
              <Navigator
                hoverClass="none"
                url={l.url}
                key={l.id}
                className={clsx(
                  "block h-96px px-32px box-border flex flex-row items-center justify-between rounded-12px bg-hex-fafafd yahei font-normal text-30px text-hex-2c2c35",
                  {
                    "mb-16px": index !== len - 1
                  }
                )}
              >
                <Text>{l.name}</Text> <ArrowRight color="#B8B8BF" style={{ fontSize: arrowSize }} />
              </Navigator>
            ))}
          </View>
        ) : null}
      </View>
    )
  }
  /** 就业方向 */
  renderTarget = () => {
    const { directions } = this.state
    const len = directions.length
    if (len <= 0) return null
    return (
      <View className="pt-88px px-30px bg-hex-fff">
        <View className="pb-34px">
          <GpBlockTitle title="就业方向" />
        </View>
        <View className="bg-hex-FAFAFD py-40px">
          <View className={styles["target-grid"]}>
            {directions.map((l, index) => (
              <Grid.Item key={index}>
                <View className={clsx("flex flex-col justify-center items-center")}>
                  <Image src={l.picture} className="w-130px h-130px rounded-8px" />
                  <View className="yahei font-normal text-28px text-hex-2c2c35 mt-20px">
                    <Text>{l.name}</Text>
                  </View>
                </View>
              </Grid.Item>
            ))}
          </View>
        </View>
      </View>
    )
  }
  /** 报考相关 */
  renderExamRel = () => {
    const htmlContent = this.state.detail?.enrollInfo || null
    return (
      <View className="pt-88px px-30px bg-hex-fff">
        <View className="pb-34px">
          <GpBlockTitle title="报考相关" />
        </View>
        {/* <View className="taro_html" dangerouslySetInnerHTML={{ __html: htmlContent }}></View> */}
        {htmlContent && (
          <View className="taro_html">
            <GpHtmlRenderer htmlBlocks={htmlContent.blocks} />
          </View>
        )}
        {/* className="yahei font-normal text-28px text-hex-2c2c35 leading-40px" */}
      </View>
    )
  }
  /** 学习资料 */
  renderLearnRel = () => {
    const { articles } = this.state
    const len = articles.length
    if (len <= 0) return null
    return (
      <View className="pt-88px px-30px bg-hex-fff">
        <View className="pb-28px">
          <GpBlockTitle title="学习资料" showArrow navigatorLink={commonUrls.news} />
        </View>
        <View className="flex flex-col">
          {/* item for loop */}
          {articles.map((l, index) => (
            <Navigator
              key={index}
              url={l.url}
              className={clsx("block ", {
                "mb-28px": index !== len - 1
              })}
            >
              <View className="flex flex-row justify-between items-center">
                <View className="yahei font-normal text-28px text-hex-2c2c35 truncate whitespace-nowrap flex-1">
                  <Text>{l.articleTitle}</Text>
                </View>
                <View className="flex-none yahei font-normal text-24px text-hex-b8b8bf ml-37px">
                  <Text>{l.updateTime}</Text>
                </View>
              </View>
            </Navigator>
          ))}
        </View>
      </View>
    )
  }
  /** 推荐院校 */
  renderSchool = () => {
    const { schools } = this.state
    if (schools.length <= 0) return null
    return (
      <View className="pt-88px px-30px bg-hex-fff">
        <View className="pb-34px ">
          <GpBlockTitle title="推荐院校" showArrow navigatorLink={commonUrls.shoolQuery} />
        </View>
        <View className="flex flex-col">
          {schools.map((l, index) => (
            <GpSchoolItem key={index} schoolItem={l} />
          ))}
        </View>
      </View>
    )
  }
  /** 推荐机构 */
  renderInstitution = () => {
    const { agencys } = this.state
    if (agencys.length <= 0) return null
    return (
      <View className="pt-88px px-30px bg-hex-fff">
        <View className="pb-34px ">
          <GpBlockTitle
            title="推荐机构"
            showArrow
            navigatorLink={commonUrls.institution}
            openType="switchTab"
          />
        </View>
        <View className="flex flex-col">
          {agencys.map((l, index) => (
            <GpInstitutionItemPure key={index} institution={l} />
          ))}
        </View>
      </View>
    )
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="mt-20px">
        <GpJumpNavs />
      </View>
    )
  }
  render(): React.ReactNode {
    if (!this.state.detail) return null
    const { pagination } = this.state
    return (
      <GpContainer>
        <View>
          {this.renderBanner()}
          {/* 美术简介 */}
          {this.renderDesc()}
          {/* 分液器 */}
          <View className="pt-20px bg-hex-fff">
            <GpPagination onChange={this.handlePageChange} pagination={pagination} />
          </View>
          {/* 就业方向 */}
          {this.renderTarget()}
          {/* 报考相关 */}
          {this.renderExamRel()}
          {/* 学习资料 */}
          {this.renderLearnRel()}
          {/* 推荐院校 */}
          {this.renderSchool()}
          {/* 推荐机构 */}
          {this.renderInstitution()}
          <View className="bg-hex-fff pb-40px"></View>
          {/* 快捷导航 */}
          {this.renderJumpNavs()}
          {/* 当前位置 */}
          <GpCurrentPort ports={ports} />
        </View>
        {/* 底部导航 */}
        <GpTabbar />
      </GpContainer>
    )
  }
}
export default SpecificExplain
